﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using SYcwpb.ViewModels;
using SYcwpb.Helpers;
using SYcwpb.Controls;
using System.Data;
using System.Threading;
using System.Windows.Markup;
using System.IO;
using System.Xml;
using System.Collections.ObjectModel;

namespace SYcwpb.Views
{
    /// <summary>
    /// DriverTeamManagerView.xaml 的交互逻辑
    /// </summary>
    public partial class DriverTeamManagerView : Window
    {
        private static DriverTeamManagerView _view = null;
        private DriverTeamViewModel _viewModel;
        private TextBlock sourceTbk = null;

        private DriverCard _sourcecard;
        public DriverCard Sourcecard
        {
            get { return _sourcecard; }
            set { _sourcecard = value; }
        }

        public DriverCard SourceDriverCard { get; set; }
        public DriverCard TargetDriverCard { get; set; }

        private ContextMenu changeDriverContextMenu;



        private DriverTeamManagerView()
        {
            InitializeComponent();

            _viewModel = new DriverTeamViewModel();

            this.DataContext = _viewModel;
        }

        public static DriverTeamManagerView GetInstance()
        {
            if (null == _view || WindowHelper.IsDisposed(_view))
                _view = new DriverTeamManagerView();

            return _view;
        }

        private void TextBlock_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            TextBlock tbk = sender as TextBlock;
            this.sourceTbk = tbk;
            if (null != tbk)
                DragDrop.DoDragDrop(tbk, tbk.Text, DragDropEffects.Copy);
        }

        private void TextBlock_DragEnter(object sender, DragEventArgs e)
        {
            string content = e.Data.GetData(DataFormats.Text).ToString();
            e.Effects = DragDropEffects.Copy;
        }

        private void TextBlock_Drop(object sender, DragEventArgs e)
        {
            TextBlock targetTbk = sender as TextBlock;
            string content = e.Data.GetData(DataFormats.Text).ToString();
            if (string.IsNullOrEmpty(content) || sourceTbk == null)
                return;

            // 这里执行一次安排交路到司机成功后，才可交换
            string error = "";
            if (_viewModel.ExchangeGroups(sourceTbk.Text, targetTbk.Text, ref error))
            {
                sourceTbk.Text = targetTbk.Text;
                targetTbk.Text = content;
            }
            if (!string.IsNullOrEmpty(error))
            {
                MessageBoxHelper.ShowError(error);
            }
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            this.WindowState = WindowState.Maximized;
            //setEvent(remainDriver);
            //setEvent(ZBDriver);
            //setEvent(BBDriver);
            //setEvent(YBDriver);
            //setEvent(XBDriver);
            BindingEvent();

            changeDriverContextMenu = new ContextMenu();
            MenuItem leftItem = new MenuItem();
            MenuItem rightItem = new MenuItem();
            MenuItem cancelChangeItem = new MenuItem();
            leftItem.Header = "申请司机";
            leftItem.Tag = 1;
            rightItem.Header = "替代司机";
            rightItem.Tag = 2;
            cancelChangeItem.Header = "取消调班";
            cancelChangeItem.Tag = 3;

            changeDriverContextMenu.Items.Add(leftItem);
            changeDriverContextMenu.Items.Add(rightItem);
            changeDriverContextMenu.Items.Add(cancelChangeItem);

            leftItem. Click+= new RoutedEventHandler(ChangeDriverContextMenuItemClick);
            rightItem.Click += new RoutedEventHandler(ChangeDriverContextMenuItemClick);
            cancelChangeItem.Click += new RoutedEventHandler(CancelChangeContextMenuItemClick);

            InitDriverComboBox();
            cbbdriver.ItemsSource = DicDriverInfo.Values;
            cbbdriver.SelectedValuePath = "userViewName";
            cbbdriver.DisplayMemberPath = "userViewNameAndUserName";
        }

        private const string isQuitUser = " and (quit is null or LTRIM(quit)='') ";

        public static int lineid = Convert.ToInt32(CONSTDATA.UserModel.Line);
        private SqlDataLayer sqlHelper = new SqlDataLayer();
        private Dictionary<int, Driver> DicDriverInfo = new Dictionary<int, Driver>();
        private void InitDriverComboBox()
        {
            
            DicDriverInfo.Clear();
            string strSql = "select user_id, user_name,user_view_name from [system_user] where user_dep_id =7 and user_line = " + lineid + isQuitUser + "  order by user_view_name";
            DataTable driverDT = sqlHelper.SelectDt(strSql);
            if (driverDT.Rows.Count > 0)
            {
                for (int i = 0; i < driverDT.Rows.Count; i++)
                {
                    Driver driver = new Driver();
                    driver.userName = driverDT.Rows[i]["user_name"].ToString();
                    driver.userViewName = driverDT.Rows[i]["user_view_name"].ToString();

                    int id = Convert.ToInt32(driverDT.Rows[i]["user_id"].ToString());

                    string item = driver.userViewName + " " + driver.userName;
                    driver.userViewNameAndUserName = item;
                    // MonDriverList.Add(item);
                    DicDriverInfo.Add(id, driver);
                }
            }
        }
        private void BindingEvent()
        {
            _viewModel.ChangeCardsCollections[0].AllowDrop = true;
            _viewModel.ChangeCardsCollections[0].Drop -= DriverChange_Drop;
            _viewModel.ChangeCardsCollections[0].Drop += DriverChange_Drop;

            _viewModel.ChangeCardsCollections[1].AllowDrop = true;
            _viewModel.ChangeCardsCollections[1].Drop -= DriverChange_Drop;
            _viewModel.ChangeCardsCollections[1].Drop += DriverChange_Drop;
           // setEvent(remainDriver);
            setEvent(ZBDriver);
            setEvent(BBDriver);
            setEvent(YBDriver);
            setEvent(XBDriver);
        }

        public void setEvent(DependencyObject obj)
        {
            List<DriverCard> collection = GetChildObjects<DriverCard>(obj, "");//


            foreach (DriverCard item in collection)//遍历这个集合  
            {
                item.AllowDrop = true;
                item.MouseLeftButtonDown -= DriverManager_MouseLeftButtonDown;
                item.MouseLeftButtonDown += DriverManager_MouseLeftButtonDown;
                item.MouseRightButtonDown -= DriverManager_MouseRightButtonDown;
                item.MouseRightButtonDown += DriverManager_MouseRightButtonDown;

                item.Drop -= DriverManager_Drop;
                item.Drop += DriverManager_Drop;
                item.DragEnter -= DriverManager_DragEnter;
                item.DragEnter += DriverManager_DragEnter;

            }
        }

        public List<T> GetChildObjects<T>(DependencyObject obj, string name) where T : FrameworkElement
        {
            DependencyObject child = null;
            List<T> childList = new List<T>();
            for (int i = 0; i <= VisualTreeHelper.GetChildrenCount(obj) - 1; i++)
            {
                child = VisualTreeHelper.GetChild(obj, i);
                if (child is T && (((T)child).Name == name || string.IsNullOrEmpty(name)))
                {
                    childList.Add((T)child);
                }
                childList.AddRange(GetChildObjects<T>(child, ""));//指定集合的元素添加到List队尾
            }
            return childList;
        }
        private void CancelChangeContextMenuItemClick(object sender, EventArgs e)
        {
            try
            {
                DriverCard card=changeDriverContextMenu.Tag as DriverCard;
                if(card==null)
                    return;
                _viewModel.CancelExchangeDriver(card);
                BindingEvent();
            }
            catch (Exception ex)
            {
                MessageBoxHelper.ShowError(ex);
            }
        }
        private void ChangeDriverContextMenuItemClick(object sender, EventArgs e)
        {
            try
            {
                MenuItem item = sender as MenuItem;
                int tag = Convert.ToInt32(item.Tag);
                DriverCard card=changeDriverContextMenu.Tag as DriverCard;
                if(card==null)
                    return;
                if (tag == 1)
                {
                    _viewModel.ChangeCardsCollections[0].Copy(card);
                    SourceDriverCard = card;
                }
                else if (tag == 2)
                {
                    _viewModel.ChangeCardsCollections[1].Copy(card);
                    TargetDriverCard = card;
                }
            }
            catch (Exception ex)
            {
                MessageBoxHelper.ShowError(ex);
            }
        }
        
        public void DriverManager_DragEnter(object sender, DragEventArgs e)
        {
    //        #region
    //        int boundary = 100;
    //        int k=2; 
    //        if (e.GetPosition(ZBDriverScrollViewer).X > ZBDriverScrollViewer.ViewportWidth - boundary
    //            &&e.GetPosition(ZBDriverScrollViewer).Y>0&&e.GetPosition(ZBDriverScrollViewer).Y<ZBDriverScrollViewer.ViewportHeight)
    //        {
    //            while (k>0)
    //            {
    //                k--;
    //                ZBDriverScrollViewer.LineRight();
    //            }
    //        }
    //        else if (e.GetPosition(ZBDriverScrollViewer).X < boundary
    //            && e.GetPosition(ZBDriverScrollViewer).Y > 0 && e.GetPosition(ZBDriverScrollViewer).Y < ZBDriverScrollViewer.ViewportHeight)
    //        {
    //            while (k > 0)
    //            {
    //                k--;
    //                ZBDriverScrollViewer.LineLeft();
    //            }
    //        }

    //        else if (e.GetPosition(YBDriverScrollViewer).X > ZBDriverScrollViewer.ViewportWidth - boundary
    //&& e.GetPosition(YBDriverScrollViewer).Y > 0 && e.GetPosition(YBDriverScrollViewer).Y < YBDriverScrollViewer.ViewportHeight)
    //        {
    //            while (k > 0)
    //            {
    //                k--;
    //                YBDriverScrollViewer.LineRight();
    //            }
    //        }
    //        else if (e.GetPosition(YBDriverScrollViewer).X < boundary
    //            && e.GetPosition(YBDriverScrollViewer).Y > 0 && e.GetPosition(YBDriverScrollViewer).Y < YBDriverScrollViewer.ViewportHeight)
    //        {
    //            while (k > 0)
    //            {
    //                k--;
    //                YBDriverScrollViewer.LineLeft();
    //            }
    //        }

    //        else if (e.GetPosition(BBDriverScrollViewer).X > BBDriverScrollViewer.ViewportWidth - boundary
    //&& e.GetPosition(BBDriverScrollViewer).Y > 0 && e.GetPosition(BBDriverScrollViewer).Y < BBDriverScrollViewer.ViewportHeight)
    //        {
    //            while (k > 0)
    //            {
    //                k--;
    //                BBDriverScrollViewer.LineRight();
    //            }
    //        }
    //        else if (e.GetPosition(BBDriverScrollViewer).X < boundary
    //            && e.GetPosition(BBDriverScrollViewer).Y > 0 && e.GetPosition(BBDriverScrollViewer).Y < BBDriverScrollViewer.ViewportHeight)
    //        {
    //            while (k > 0)
    //            {
    //                k--;
    //                BBDriverScrollViewer.LineLeft();
    //            }
    //        }

    //        else if (e.GetPosition(XBDriverScrollViewer).X > XBDriverScrollViewer.ViewportWidth - boundary
    //&& e.GetPosition(XBDriverScrollViewer).Y > 0 && e.GetPosition(XBDriverScrollViewer).Y < XBDriverScrollViewer.ViewportHeight)
    //        {
    //            while (k > 0)
    //            {
    //                k--;
    //                XBDriverScrollViewer.LineRight();
    //            }
    //        }
    //        else if (e.GetPosition(XBDriverScrollViewer).X < boundary
    //            && e.GetPosition(XBDriverScrollViewer).Y > 0 && e.GetPosition(XBDriverScrollViewer).Y < XBDriverScrollViewer.ViewportHeight)
    //        {
    //            while (k > 0)
    //            {
    //                k--;
    //                XBDriverScrollViewer.LineLeft();
    //            }
    //        }

    //        #endregion

            string content = e.Data.GetData(DataFormats.Text).ToString();
            e.Effects = DragDropEffects.Copy;

            
        }
        public void DriverManager_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
        {
            changeDriverContextMenu.Tag = sender;
            changeDriverContextMenu.IsOpen = true;
        }
        public void DriverManager_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {

            DriverCard card = sender as DriverCard;
            if (card != null)

            {
                if (card.JobNum == null) { return; }
                string content = card.JobNum + "," + card.Driver_group;
                Sourcecard = (DriverCard)e.Source;


                //_viewModel.SourceCardsCollections.Add(Sourcecard);
                if (card.JobNum != null && card.JobNum != "")
                {
                    DragDrop.DoDragDrop(card, content, DragDropEffects.Copy);
                }
            }
        }
        public void DriverChange_Drop(object sender, DragEventArgs e)
        {
            try
            {
                if (Sourcecard != null)
                {
                    DriverCard card = (DriverCard)sender;
                    card.Copy(Sourcecard);
                    if (card == _viewModel.ChangeCardsCollections[0])
                        SourceDriverCard = Sourcecard;
                    else
                        TargetDriverCard = Sourcecard;
                }

            }
            catch (Exception ex)
            {
                MessageBoxHelper.ShowError(ex);
            }
        }
        public void DriverManager_Drop(object sender, DragEventArgs e)
        {
            //源卡片司机ID
            if (Sourcecard != null)
            {
                string sourceDriverID = Sourcecard.Driverid;
                //目标卡片司机ID
                DriverCard Targetcard = (DriverCard)sender;
                string targetDriverID = Targetcard.Driverid;
                if (Sourcecard == Targetcard)
                {
                    return;
                }

                //变换司机
                _viewModel.ExchangeDriver(Targetcard, Sourcecard);

                //重新绑定事情
                BindingEvent();
                /*  string[] Job_num_Group = e.Data.GetData(DataFormats.Text).ToString().Split(',');

                  string Sjob_num, Sgroup;
                  if (Job_num_Group.Length == 2)
                  {
                      Sjob_num = Job_num_Group[0]; Sgroup = Job_num_Group[1];
                      if (Sgroup == "") { Sgroup = null; }
                      DriverCard Scard = GetSourceDriverCard(Sjob_num, Sgroup);
                      if (Scard == null) { return; }
                      //这里来一个判断，只有在该班组出勤前能进行轮换 
                      if (!CheckCanExchange(Sgroup, Targetcard.Driver_group))
                      {
                          MessageBox.Show("该班组正在执勤，不能进行人员交换，请确认！", "系统信息");
                          return;
                      }
                      if (Sgroup == null && Targetcard.Driver_group == null)
                      {
                          Targetcard.Exchange(ref Scard);  //名牌信息交换
                          return;
                      }

                      //if (!IsAddJiaoLu) { MessageBox.Show("今天尚没执行安排交路到司机，名牌交换功能不可用！","");return; }

                      if (MessageBox.Show("确定要进行调班吗？", "信息确认", MessageBoxButton.OKCancel) != MessageBoxResult.OK)
                      {
                          return;
                      }
                      if (Targetcard.Driver_group == "zb" && Scard.Driver_group == "zb")
                      {
                          Targetcard.Exchange(ref Scard, true);  //两个早班名牌信息交换
                      }
                      else if (Targetcard.Driver_group == "zb" || Scard.Driver_group == "zb")
                      {
                          Targetcard.Exchange(ref Scard, false);  //含有早班名牌信息交换
                      }
                      else
                      {
                          Targetcard.Exchange(ref Scard);  //不含早班名牌信息交换
                      }
                      //Targetcard.Exchange(ref Scard);  //名牌信息交换
                      UpdateToDB(Targetcard); //更新到数据库
                      UpdateToDB(Scard);*/
            }
        }

        private void ChangeButton_Click(object sender, RoutedEventArgs e)
        {
            try {

                if (SourceDriverCard==null||TargetDriverCard==null||SourceDriverCard.DriverName == string.Empty || TargetDriverCard.DriverName == string.Empty)
                {
                    return;
                }
                else if (SourceDriverCard.DriverName == TargetDriverCard.DriverName && SourceDriverCard.Driverid == TargetDriverCard.Driverid)
                {
                    MessageBoxHelper.ShowWarning("调班司机不能相同");
                    return;
                }
                string sourceDriverID = SourceDriverCard.Driverid;
                //目标卡片司机ID
                string targetDriverID = TargetDriverCard.Driverid;
                //变换司机
                _viewModel.ExchangeDriver(SourceDriverCard, TargetDriverCard);
                //重新绑定事情
                BindingEvent();
                _viewModel.ChangeCardsCollections[0].Copy(null);
                _viewModel.ChangeCardsCollections[1].Copy(null);
                SourceDriverCard = null;
                TargetDriverCard = null;
            }
            catch (Exception ex)
            {
                MessageBoxHelper.ShowError(ex);
            }
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {

        }

        private void SelDriverByListView(object sender, RoutedEventArgs e)
        {
            try
            {
                if (cbbdriver.SelectedValue == null)
                    return;
                string driverName = cbbdriver.SelectedValue.ToString();
                ClassTeamSeach(driverName, _viewModel.CardsCollectionsZB, ZBDriverScrollViewer,ZBDriver);
                ClassTeamSeach(driverName, _viewModel.CardsCollectionsBB, BBDriverScrollViewer, BBDriver);
                ClassTeamSeach(driverName, _viewModel.CardsCollectionsYB, YBDriverScrollViewer, YBDriver);
                ClassTeamSeach(driverName, _viewModel.CardsCollectionsXB, XBDriverScrollViewer, XBDriver);

                for (int i = 0; i < _viewModel.CardsCollectionsLeft.Count; i++)
                {
                    var item = _viewModel.CardsCollectionsLeft[i];
                    DriverCard card = (DriverCard)remainDriver.Items[i];
                    if (item.DriverName == driverName)
                    {
                        rightScrollViewer.ScrollToHorizontalOffset((i + 1) * itemWidth - rightScrollViewer.ActualWidth / 2);
                        card.Highlight();
                    }
                    else
                    {
                        card.CancelHightlight();
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        private const int itemWidth = 80;
        private void ClassTeamSeach(String driverName, ObservableCollection<DriverCard> list,ScrollViewer scroll,ItemsControl ctrl)
        {
            
            for (int i = 0; i < list.Count; i++)
            {
                var item = list[i];
                DriverCard card = (DriverCard)ctrl.Items[i];
                if (item.DriverName == driverName)
                {
                    scroll.ScrollToHorizontalOffset((i + 1) * itemWidth - scroll.ActualWidth / 2);
                    card.Highlight();
                }
                else
                {
                    card.CancelHightlight();
                }
            }
        }
    }
}
